package com.luych.toolbox.docker.service.job;

import com.luych.toolbox.common.enums.DockerServerStatus;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketEventPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketLetterPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketNoticePublisher;
import com.luych.toolbox.common.feign.param.gateway.center.WebSocketEvent;
import com.luych.toolbox.docker.service.constant.Constant;
import com.luych.toolbox.docker.service.dao.DockerServerDao;
import com.luych.toolbox.docker.service.entity.DockerServer;
import com.luych.toolbox.docker.service.sdk.DockerClient;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class DockerServerHealthCheckJob extends QuartzJobBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(DockerServerHealthCheckJob.class);

    private final BusProperties busProperties;
    private final ApplicationEventPublisher applicationEventPublisher;
    private final DockerServerDao dockerServerDao;

    public DockerServerHealthCheckJob(BusProperties busProperties,
                                      ApplicationEventPublisher applicationEventPublisher,
                                      DockerServerDao dockerServerDao) {
        this.busProperties = busProperties;
        this.applicationEventPublisher = applicationEventPublisher;
        this.dockerServerDao = dockerServerDao;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String id = context.getJobDetail().getJobDataMap().getString("id");

        WebSocketLetterPublisher letterPublisher = new WebSocketLetterPublisher(busProperties, applicationEventPublisher);
        WebSocketNoticePublisher noticePublisher = new WebSocketNoticePublisher(busProperties, applicationEventPublisher);
        WebSocketEventPublisher eventPublisher = new WebSocketEventPublisher(busProperties, applicationEventPublisher);

        DockerServer dockerServer = dockerServerDao.findById(id).orElseThrow(() ->
                new JobExecutionException(Constant.DOCKER_SERVER_NOT_FOUND));
        DockerServerStatus status;
        LOGGER.info("start to check docker server {} status...", dockerServer.getName());
        try {
            DockerClient dockerClient = new DockerClient(dockerServer.getUrl());
            dockerClient.system().ping();
            status = DockerServerStatus.NORMAL;
            LOGGER.info("docker server {} connect success", dockerServer.getName());
        } catch (Exception e) {
            LOGGER.error("docker server {} connect error: {}", dockerServer.getName(), e.getMessage());
            status = DockerServerStatus.ABNORMAL;
        }
        if (!dockerServer.getStatus().equals(status)) {
            String message = "容器宿主机连接状态通知";
            if (dockerServer.getStatus() != DockerServerStatus.ABNORMAL && status == DockerServerStatus.ABNORMAL) {
                String content = "容器宿主机[" + dockerServer.getName() + "]连接异常，请注意修复！";
                letterPublisher.error(dockerServer.getOwnerId(), message, content);
                noticePublisher.error(dockerServer.getOwnerId(), content);
                eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DOCKER_SERVER_ABNORMAL, dockerServer.getId()));
            } else if (dockerServer.getStatus() != DockerServerStatus.NORMAL && status == DockerServerStatus.NORMAL) {
                String content = "容器宿主机[" + dockerServer.getName() + "]连接正常。";
                letterPublisher.success(dockerServer.getOwnerId(), message, content);
                noticePublisher.success(dockerServer.getOwnerId(), content);
                eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DOCKER_SERVER_NORMAL, dockerServer.getId()));
            }

            dockerServer.setStatus(status);
            dockerServerDao.save(dockerServer);
        }
    }
}
